const mongoose = require('mongoose')
mongoose.set('useFindAndModify', false)
const moment = require('moment')

// 数据库地址
//const url = "mongodb+srv://root:20201113@wes.z45uy.mongodb.net/website"
const url = "mongodb://localhost:27017/king"

mongoose.connect(url, { useNewUrlParser: true }, function (err) {
  if (err) {
    console.log(err)
  } else {
    console.log('Connection success!')
  }
})
const Schema = mongoose.Schema

// 验证码
let checkcodeSchema = new Schema({
  token: String,
  code: String
}, {
  versionKey: false
})

// 用户
let userSchema = new Schema({
  nickname: String,
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  avatar: { type: String, default: '' },
  token: { type: String, default: '' },
  deptId: Number,
  roleId: Number,
  createTime: {
    type: String,
    default: () => moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  }
}, {
  versionKey: false,  // 增加的文档不会有__v字段
  timestamps: { createdAt: 'createTime' }
})

// 文章
let articleSchema = new Schema({
  title: String,
  description: String,
  content: String,
  type: String,
  avatar: String,
  image: Array,
  creater: String,
  // TODO:这里很重要，需要什么记得加上
  userId: {
    type: mongoose.Schema.ObjectId,
    ref: 'User'
  },
  createTime: {
    type: Date,
    default: Date.now(),
    get: v => moment(v).format('YYYY-MM-DD HH:mm:ss')
  },
  updateTime: {
    type: Date,
    default: Date.now(),
    get: v => moment(v).format('YYYY-MM-DD HH:mm:ss')
  }
}, {
  versionKey: false,
  timestamps: { createdAt: 'createTime', updatedAt: 'updateTime' }
})
articleSchema.set('toJSON', { getters: true });

exports.CheckCode = mongoose.model('Checkcode', checkcodeSchema)
exports.User = mongoose.model('User', userSchema)
exports.Article = mongoose.model('Article', articleSchema)
